const http = require('http')
const qs = require('querystring')
const formidable = require('formidable')

const show = (res) => {
  const html = `
<form method="post" action="/" enctype="multipart/form-data">
<p><input type="text" name="name" /></p>
<p><input type="file" name="file" required/></p>
<p><input type="submit" value="Upload" /></p>
</form>`
  res.setHeader('Content-Type', 'text/html')
  res.setHeader('Content-Length', Buffer.byteLength(html))
  res.end(html)
}

const isFormData = (req) => {
  const type = req.headers['content-type'] || ''
  return 0 === type.indexOf('multipart/form-data')
}

const upload = (req, res) => {
  if (!isFormData(req)) {
    res.statusCode = 400
    res.end('Bad Request: expecting multipart/form-data')
    return
  }
  const form = new formidable.IncomingForm()
  let _file
  form.on('field', (field, value) => {
    console.log('>>> field', field)
    console.log('>>> value', value)
  })
  form.on('file', (name, file) => {
    console.log('>>> name', name)
    console.log('>>> file', file)
    _file = file
  })
  form.on('end', () => {
    res.end('Upload complete!\n' + JSON.stringify(_file, null, 2))
  })
  form.on('progress', (bytesReceived, bytesExpected) => {
    const percent = Math.floor(bytesReceived/bytesExpected * 100)
    console.log(`${bytesReceived} of ${bytesExpected}, ${percent}%`)
  })
  form.parse(req)
}

const badRequest = (res) => {
  res.statusCode = 400
  res.setHeader('Content-Type', 'text/plain')
  res.end('Bad Request')
}
const notFound = (res) => {
  res.statusCode = 404
  res.setHeader('Content-Type', 'text/plain')
  res.end('Not Found')
}

const server = http.createServer((req, res) => {
  if ('/' === req.url) {
    switch (req.method) {
      case 'GET':
        show(res)
        break
      case 'POST':
        upload(req, res)
        break
      default:
        badRequest(res)
    }
  } else {
    notFound(res)
  }
})
server.listen(3000, () => {
  console.log('HTTP server running in port: http://localhost:3000')
})
